package com.example.controlller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.example.common.Result;
import com.example.entity.User;
import com.example.service.UserService;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {
    @Resource
    private UserService userService;

    // 查询所有
    @GetMapping("/selectAll")
    public Result selectAll(User user) {
        List<User> userList = userService.selectAll(user);
        return Result.success(userList, "查询成功");
    }

    // 分页查询
    @GetMapping("/selectPage")
    public Result selectPage(@RequestParam(defaultValue = "1") Integer pageNum,
                             @RequestParam(defaultValue = "10") Integer pageSize,
                             User user) {
        PageInfo<User> pageInfo = userService.selectPage(pageNum, pageSize, user);
        return Result.success(pageInfo, "查询成功");
    }

    // 新增用户
    @PostMapping("/add")
    public Result add(@RequestBody User user) {
        userService.insert(user);
        return Result.success();
    }

    // 修改用户
    @PutMapping("/update")
    public Result update(@RequestBody User user) {
        userService.updateById(user);
        return Result.success();
    }

    // 删除用户
    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable Integer id) {
        userService.deleteById(id);
        return Result.success();
    }

    // 批量删除
    @DeleteMapping("/deleteBatch")
    public Result deleteBatch(@RequestBody List<User> ids) {
        userService.deleteBatch(ids);
        return Result.success();
    }

    // ... existing code ...

    /**
     * 导出用户数据为Excel文件
     * 该方法将所有用户信息导出为Excel文件并提供下载
     *
     * @param response HTTP响应对象，用于设置响应头和输出流
     * @throws Exception 导出过程中可能抛出的异常
     */
    @GetMapping("/export")
    public void exportExcel(User user, HttpServletResponse response) throws Exception {
        if (StrUtil.isNotBlank(user.getIds())) user.setIdsArr(user.getIds().split(","));
        // 获取所有用户数据
        List<User> list = userService.selectAll(user);

        // 创建Excel写入器并设置列名别名
        ExcelWriter writer = ExcelUtil.getWriter(true);
        writer.addHeaderAlias("username", "用户名");
        writer.addHeaderAlias("realName", "真实姓名");
        writer.addHeaderAlias("email", "邮箱");
        writer.addHeaderAlias("nickname", "昵称");
        writer.setOnlyAlias(true);
        writer.write(list);

        // 设置响应头信息，指定文件名和内容类型
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = URLEncoder.encode("用户信息", StandardCharsets.UTF_8);
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");

        // 输出Excel文件到客户端
        ServletOutputStream outputStream = response.getOutputStream();
        writer.flush(outputStream);
        writer.close();
        outputStream.close();
    }

    // ... existing code ...

    /**
     * 从Excel文件导入用户数据
     * 该方法读取上传的Excel文件，解析其中的用户数据并保存到数据库
     *
     * @param file 上传的Excel文件
     * @return 操作结果，成功或失败
     * @throws IOException 文件读取异常
     */
    @PostMapping("/import")
    public Result importExcel(MultipartFile file) throws Exception {
        System.out.println(file);
        InputStream inputStream = file.getInputStream();
        ExcelReader reader = ExcelUtil.getReader(inputStream);
        reader.addHeaderAlias("用户名", "username");
        reader.addHeaderAlias("真实姓名", "realName");
        reader.addHeaderAlias("邮箱", "email");
        reader.addHeaderAlias("昵称", "nickname");
        List<User> list = reader.readAll(User.class);
        for (User user : list) {
            userService.insert(user);
        }
        User user = new User();
        List<User> userList = userService.selectAll(user);
        return Result.success(userList,"批量导入成功");
    }
}
